package com.tang.module.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tang.common.constant.BusinessConstant;
import com.tang.module.system.entity.Role;
import com.tang.module.system.entity.RoleInterface;
import com.tang.module.system.mapper.InterfaceConfigurationMapper;
import com.tang.module.system.entity.InterfaceConfiguration;
import com.tang.module.system.mapper.RoleInterfaceMapper;
import com.tang.module.system.mapper.RoleMapper;
import com.tang.module.system.service.InterfaceConfigurationService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 业务接口配置表(InterfaceConfiguration)表服务实现类
 *
 * @author tang
 * @since 2022-01-21 12:59:21
 */
@Service("interfaceConfigurationService")
public class InterfaceConfigurationServiceImpl extends ServiceImpl<InterfaceConfigurationMapper, InterfaceConfiguration> implements InterfaceConfigurationService {


    @Resource
    private RoleMapper roleMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private InterfaceConfigurationMapper interfaceConfigurationMapper;

    @Resource
    private RoleInterfaceMapper roleInterfaceMapper;



    @Override
    public List<Role> getRole(Long id) {
        return roleMapper.byInterfaceId(id);
    }

    @Override
    public boolean cacheRefresh() {
        List<InterfaceConfiguration> interfaceConfigurations = interfaceConfigurationMapper.selectList(null);
        for (InterfaceConfiguration interfaceConfiguration : interfaceConfigurations) {
            //存在就覆盖，不存在就新增
            stringRedisTemplate.opsForHash().put(
                    BusinessConstant.INTERFACE_RESTRICTION_HASH,
                    interfaceConfiguration.getMethod()+ interfaceConfiguration.getSign(),
                    String.valueOf(interfaceConfiguration.getInterfaceType()));
        }
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRole(Long id, List<Long> rid) {
        roleInterfaceMapper.delete(Wrappers.<RoleInterface>lambdaQuery().eq(RoleInterface::getInterfaceId,id));
        for (Long aLong : rid) {
            //新增角色和接口关联关系
            roleInterfaceMapper.insert(new RoleInterface().setInterfaceId(id).setRoleId(aLong));
        }
        return true;
    }
}
